<?php

namespace app\admin\controller\basic;

use app\common\controller\Backend;
use think\Db;
use fast\Random;

/**
 * 教师列表
 */
class Teacher extends Backend
{

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
        $ruleList = Db::name("classes")->select();
        $this->rulelist = is_array($ruleList) ? $ruleList : [];
        $ruledata = [];
        foreach ($this->rulelist as $k => &$v) {
            $ruledata[$v['id']] = $v['name'];
        }
        $this->view->assign('flagList', $ruledata);
        $schoolList = Db::name("school")->select();
        $this->schoolList = is_array($schoolList)? $schoolList : [];
        $schooldata = [0 => __('None')];
        foreach ($this->schoolList as $k => &$v) {
            $schooldata[$v['id']] = $v['name'];
        }
        $this->view->assign('schoolList', $schooldata);
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            // 获取请求参数
            $params = $this->request->param();

            // 查询数据（带分页）
            $list = $this->model
                ->with('school')
                ->where('type', 2)
                ->order($params['sort'] ?? 'id', $params['order'] ?? 'desc')
                ->paginate([
                    'list_rows' => $params['limit'] ?? 10,
                    'page'      => ($params['offset'] / $params['limit'] + 1) ?? 1
                ]);

            // 返回标准JSON格式
            $result = [
                "total" => $list->total(),
                "rows"  => $list->items()
            ];

            return json($result);
        }

        // 非AJAX请求返回视图
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {

        if ($this->request->isPost()) {
            //  获取提交的数据
            $data = $this->request->post('row/a');
            if (empty($data['username']) || empty($data['password']) || empty($data['email']) || empty($data['mobile']) || empty($data['school_id'])) {
                $this->error('参数不足');
            }

            $email = $this->model->where('email', $data['email'])->find();
            if ($email) {
                $this->error('该邮箱已存在');
            }

            $mobile = $this->model->where('mobile', $data['mobile'])->find();
            if ($mobile) {
                $this->error('该手机号已存在');
            }

            $classIds = [];
            if (!empty($data['classes_id'])) {
                $classIds = array_filter(array_map('intval', (array)$data['classes_id']));
                $classIds = array_values(array_unique($classIds)); // 去重
            }
            unset($data['classes_id']);

            $data['type'] = 2;
            $data['salt'] = Random::alnum();
            $data['password'] = $this->getEncryptPassword($data['password'], $data['salt']);
            
            // 开始事务处理
            Db::startTrans();
            try {
                // 保存教师信息
                $result = $this->model->save($data);
                $teacher_id = $this->model->id;
                
                // 检查教师保存是否成功
                if ($result && $teacher_id) {
                    // 保存班级关联关系
                    if (!empty($classIds)) {
                        // 先准备好班级关联数据
                        $insertData = array_map(function($classId) use ($teacher_id) {
                            return [
                                'teacher_id' => $teacher_id,
                                'classes_id' => $classId
                            ];
                        }, $classIds);
                        
                        // 批量插入班级关联数据
                        $relationModel = Db::name('teacher_classes_relation');
                        $relationModel->insertAll($insertData);
                    }
                    // 提交事务
                    Db::commit();
                } else {
                    throw new \Exception('保存教师信息失败');
                }
            } catch (\Exception $e) {
                // 事务回滚
                Db::rollback();
                // 捕获异常并返回错误信息
                $this->error('添加失败: ' . $e->getMessage());
            }
        }
        return parent::add();
    }

    /**
     * 编辑
     * @param $ids
     */
    public function edit($ids = null)
    { 
        if ($this->request->isPost()) {
            $data = $this->request->post('row/a');
    
            $row = $this->model->get($ids);
            $classIds = [];
            if (!empty($data['classes_id'])) {
                $classIds = array_filter(array_map('intval', (array)$data['classes_id']));
                $classIds = array_values(array_unique($classIds)); // 去重
            }
            unset($data['classes_id']);
    
            Db::startTrans();
            try {
                // 更新数据库
                $result = $row->save($data);
                if ($result === false) {
                    throw new \Exception('更新失败');
                }
    
                if (!empty($ids)) {
                    $relationModel = Db::name('teacher_classes_relation');
                    $relationModel->where('teacher_id', $ids)->delete();
    
                    if (!empty($classIds)) {
                        $insertData = [];
                        foreach ($classIds as $classId) {
                            $insertData[] = [
                                'teacher_id' => $ids,
                                'classes_id' => $classId
                            ];
                        }
                        $relationModel->insertAll($insertData);
                    }
                }
    
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('更新失败: '. $e->getMessage());
            }
        }
    
        $row = $this->model->get($ids);
        $relatedClasses = Db::name('teacher_classes_relation')
            ->where('teacher_id', $ids)
            ->column('classes_id');
        $schooldata = Db::name('school')
            ->where('id', $row['school_id'])
            ->value('id');
            
        $this->view->assign([
            'row' => $row,
            'relatedClasses' => $relatedClasses,
            'schooldata' => $schooldata
        ]);
    
        return parent::edit($ids);
    }

    /**
    * 删除
    * @param $ids
    */
    public function del($ids = null)
    {
        if ($ids) {
            $rows = $this->model->where('id', 'in', $ids)->delete();
            if ($rows) {
                Db::name('teacher_classes_relation')->where('teacher_id', 'in', $ids)->delete();
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }
        $this->error('请选择要删除的记录');
    }

    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

}